package dialog;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.zx.theline.jclr.JclrActivity;
import com.example.zx.theline.R;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;


import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import GsonBean.JdjclrxqBean;
import GsonBean.RjhSgxmListBean;
import GsonBean.RjhsgxmList;
import GsonBean.SuccessBean;
import GsonBean.post.SaveCaoGaoPost;
import Utils.DateUtil;
import Utils.RefreshManager;
import app.MyApplication;
import base.BaseDialog;
import network.BaseCallBack;
import network.NetWorkApi;
import network.ObjectHttpResponseHandler;
import Utils.MyToast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by zx on 2017/4/6.
 */

//点击提交完成 判断 检查完成 还是整改下达

public class TjwcDialog extends BaseDialog implements View.OnClickListener {

    //施工停工标记
    boolean isShutDown = true;
    //
//    RadioButton shi;
//    RadioButton fou;
    Spinner spinner;

    TextView fxrq;
    TextView tzrq;
    TextView fldw;
    TextView flr;
    TextView zgtj;
    RelativeLayout zgqk;
    TextView gb;
    TextView tgxmtextview;
    EditText fxwt;
    ImageView back;
    LinearLayout tgxm_layout;


    SaveCaoGaoPost mSaveCaoGaoPost;
    //施工项目列表
    RjhsgxmList mRjhsgxmList;

    SpinnerAdapter mSpinnerAdapter;
    List<RjhSgxmListBean> sgxmList;

    JdjclrxqBean mJdjclrxqBean;

    //spinner是否第一次加载
    boolean isSpinnerFirst = true;

    Activity BaseActivity;

    public TjwcDialog(Context context, SaveCaoGaoPost mSaveCaoGaoPost, RjhsgxmList mRjhsgxmList, JdjclrxqBean mJdjclrxqBean, Activity activity) {
        super(context, R.style.AppTheme);
        this.mSaveCaoGaoPost = mSaveCaoGaoPost;
        this.mRjhsgxmList = mRjhsgxmList;
        this.mJdjclrxqBean = mJdjclrxqBean;
        BaseActivity = activity;
    }

    public TjwcDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_tjwc);
        InitView();
        InitData();
        InitListen();
    }

    @Override
    protected void InitView() {

        spinner = (Spinner) findViewById(R.id.spinner);
        fxrq = (TextView) findViewById(R.id.fxrq);
        tzrq = (TextView) findViewById(R.id.tzrq);
        fldw = (TextView) findViewById(R.id.fldw);
        flr = (TextView) findViewById(R.id.flr);
        zgtj = (TextView) findViewById(R.id.zgtj);
        zgqk = (RelativeLayout) findViewById(R.id.zgqk);
        gb = (TextView) findViewById(R.id.gb);
        fxwt = (EditText) findViewById(R.id.fxwt);
        back = (ImageView) findViewById(R.id.back);
        tgxmtextview = (TextView) findViewById(R.id.tgxmtextview);
        tgxm_layout = (LinearLayout) findViewById(R.id.tgxm_layout);


        if (isShutDown) {
            tgxm_layout.setVisibility(View.VISIBLE);


        } else {
            tgxm_layout.setVisibility(View.GONE);

        }
    }

    @Override
    protected void InitData() {
        sgxmList = new ArrayList<>();
//       第一次加载spinner 输入 true 去除默认view
        setSpinnerAdapter(true);
        fldw.setText(MyApplication.getmLoginUser().getUserUnitName());
        flr.setText(MyApplication.getmLoginUser().getTrueName());

        //将检查情况内容填写入发现问题
        fxwt.setText(mSaveCaoGaoPost.getJcqk());

        if (mJdjclrxqBean.getRjdjhjcbInfo().getSfjytg() != null) {
            //发现日期读检查日期
            fxrq.setText(mJdjclrxqBean.getRjdjhjcbInfo().getJcrq());
            //通知日期读当前日期
            tzrq.setText(DateUtil.getCurDate());
        }

        fxrq.setText(mJdjclrxqBean.getRjdjhjcbInfo().getJcrq());
        tzrq.setText(DateUtil.getCurDate());
    }

    @Override
    protected void InitListen() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TjwcDialog.this.dismiss();
            }
        });
        //发现日期
        fxrq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] date = {};
                String mYear;
                String mMonth;
                String mDay;
                //如果textview中存在日期 获取该日期显示在datapickdialog上
                if (isDate(fxrq.getText().toString())) {
                    date = fxrq.getText().toString().split("-");
                }
                //data为空 jcrq框内没有数据
                if (date.length < 1) {
                    mYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                    mMonth = String.valueOf(Calendar.getInstance().get(Calendar.MONTH));
                    mDay = String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
                } else {
                    mYear = date[0];
                    mMonth = date[1];
                    mDay = date[2];
                }
                new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        fxrq.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    }
                }, Integer.parseInt(mYear), Integer.parseInt(mMonth) - 1, Integer.parseInt(mDay)).show();
            }
        });
        //通知日期
        tzrq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] date = {};
                String mYear;
                String mMonth;
                String mDay;
                //如果textview中存在日期 获取该日期显示在datapickdialog上
                if (isDate(tzrq.getText().toString())) {
                    date = tzrq.getText().toString().split("-");
                }
                //data为空 jcrq框内没有数据
                if (date.length < 1) {
                    mYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
                    mMonth = String.valueOf(Calendar.getInstance().get(Calendar.MONTH));
                    mDay = String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));
                } else {
                    mYear = date[0];
                    mMonth = date[1];
                    mDay = date[2];
                }
                new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        tzrq.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    }
                }, Integer.parseInt(mYear), Integer.parseInt(mMonth) - 1, Integer.parseInt(mDay)).show();
            }
        });


        //清空输入信息
        zgqk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CleanAllData();
            }
        });
        //关闭dialog
        gb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TjwcDialog.this.dismiss();
            }
        });

        //提交
        zgtj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fxwt.getText().length() > 0 && fxwt.getText().toString().trim().length() == 0) {
                    MyToast.showToast("请不要输入空格");
                    return;
                }
                if (isShutDown && tgxmtextview.getText().equals("")) {
                    MyToast.showToast("请选择停工项目");
                    return;
                }
                if (!idEmpty()) {

                    MyApplication.ShowWaitDialog(getContext());

//                    整改提交
                    if (isShutDown) {
                        //停工标记 停工 1
                        mSaveCaoGaoPost.setSfjytg("1");
                        String tgxmid = "";
                        for (int i = 0; i < sgxmList.size(); i++) {
                            tgxmid += sgxmList.get(i).getSgxmlbzdId() + ",";
                        }
                        if (tgxmid.length() != 0) {
                            tgxmid = tgxmid.substring(0, tgxmid.length() - 1);

                        }
                        mSaveCaoGaoPost.setTgxmId(tgxmid);
                        mSaveCaoGaoPost.setTgxmmc(tgxmtextview.getText().toString());
                        //2017.7.20新增字段，保存站段长同意并确定的停工项目
                        mSaveCaoGaoPost.setJcbtgxmId(tgxmid);

                    } else {
                        //停工标记 不停工 0
                        mSaveCaoGaoPost.setSfjytg("0");
                    }

                    mSaveCaoGaoPost.setFxsj(fxrq.getText().toString());
                    mSaveCaoGaoPost.setTzrq(tzrq.getText().toString());
                    mSaveCaoGaoPost.setFldw(fldw.getText().toString());
                    mSaveCaoGaoPost.setFlrName(flr.getText().toString());
                    mSaveCaoGaoPost.setFxwt(fxwt.getText().toString());
                    Gson g=new Gson();
                    String  s=g.toJson(mSaveCaoGaoPost);
                    NetWorkApi.Zgtj(mSaveCaoGaoPost, new BaseCallBack<SuccessBean>() {
                                @Override
                                public void Success(Call<SuccessBean> call, Response<SuccessBean> response) {
                                    try {
                                        SuccessBean mBean = response.body();
                                        if (mBean.getMsg().equals("success")) {
                                            MyToast.showToast("整改提交提交成功");
                                            RefreshManager.Jdjc.RefreshJdjclrxx();
                                            RefreshManager.Jdjc.RefreshJdjcdcl();
                                            RefreshManager.Jdjc.RefreshJdjcycl();

                                            TjwcDialog.this.dismiss();
                                            getContext().startActivity(new Intent(getContext(), JclrActivity.class));
                                        } else {
                                            MyToast.showToast("提交失败");
                                        }
                                        MyApplication.HideWaitDialog();
                                    } catch (Exception e) {
                                        MyToast.showFail();
                                    }
                                }

                                @Override
                                public void Failure(Call<SuccessBean> call, Throwable t) {
                                    MyToast.showFail();

                                }

                                @Override
                                public void onFinally() {

                                }
                            }
                    );
                }
            }
        });
    }

    // 重新设置spinner数据
    public void setSpinnerAdapter(final boolean flag) {

        if (flag) {
            isSpinnerFirst = true;
        }

        mSpinnerAdapter = new SpinnerAdapter();
        spinner.setAdapter(mSpinnerAdapter);
        //取消spinner默认选中项
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isSpinnerFirst) {
                    view.setVisibility(View.INVISIBLE);
                }

                isSpinnerFirst = false;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }


    //判断字符串 是否为日期
    public boolean isDate(String s) {
        boolean flag;
        String reg = "([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(s);
        flag = matcher.matches();
        return flag;
    }


    public void addSgxm(int position) {

        sgxmList.add(mRjhsgxmList.getRjhSgxmList().get(position));
        String s = sgxmList.toString();
        s = s.substring(1, s.length() - 1);
        tgxmtextview.setText(s);
    }

    public void DelectSgxm(int position) {

        sgxmList.remove(mRjhsgxmList.getRjhSgxmList().get(position));
        String s = sgxmList.toString();
        s = s.substring(1, s.length() - 1);
        tgxmtextview.setText(s);
    }


    //清空当前页面所有数据
    private void CleanAllData() {
//        radiogroup.clearCheck();
        fxrq.setText("");
        tzrq.setText("");
        mSpinnerAdapter = new SpinnerAdapter();
        spinner.setAdapter(mSpinnerAdapter);
        setSpinnerAdapter(true);
        sgxmList.clear();
        tgxmtextview.setText("");
    }

    private boolean idEmpty() {
        if (fxrq.getText().toString().equals("") || tzrq.getText().toString().equals("") ||
                fldw.getText().toString().equals("") || flr.getText().toString().equals("")
                || fxwt.getText().toString().equals("")) {
            MyToast.showToast("请将数据填写完整");
            return true;
        } else return false;
    }


    @Override
    public void onClick(View v) {

    }

    class SpinnerAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mRjhsgxmList.getRjhSgxmList().size();
        }

        @Override
        public Object getItem(int position) {
            return mRjhsgxmList.getRjhSgxmList().get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder mViewHolder;
            if (convertView == null) {
                convertView = View.inflate(getContext(), R.layout.bcfxd_listview, null);
                mViewHolder = new ViewHolder();
                mViewHolder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }

            mViewHolder.mCheckBox.setText(mRjhsgxmList.getRjhSgxmList().get(position).getSgxmmc());
            mViewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        addSgxm(position);
                    } else {
                        DelectSgxm(position);
                    }
                }
            });
            //2017.7.0. 新增 spinner 选中已经是停工的项目
            if (mRjhsgxmList.getRjhSgxmList().get(position).isTgXm()) {
                mViewHolder.mCheckBox.setChecked(true);
            }
            return convertView;
        }

        class ViewHolder {
            CheckBox mCheckBox;
        }
    }

    public void isShutDown(boolean isShutDown) {
        this.isShutDown = isShutDown;
    }

    @Override
    public void show() {
        super.show();
        Window dialogwindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogwindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialogwindow.setAttributes(lp);
        this.setCanceledOnTouchOutside(false);
    }
}
